package MallSecret

import (
	"fmt"
	CoreSQL "gitee.com/fotomxq/weeekj_core/v5/core/sql"
	CoreSQLPages "gitee.com/fotomxq/weeekj_core/v5/core/sql/pages"
	Router2SystemConfig "gitee.com/fotomxq/weeekj_core/v5/router2/system_config"
	"github.com/lib/pq"
	"sort"
	"strings"
)

// ArgsGetSecondList 获取秒杀商品列表
type ArgsGetSecondList struct {
	//分页
	Pages CoreSQLPages.ArgsDataList `json:"pages"`
	//组织ID
	// -1 跳过
	OrgID int64 `db:"org_id" json:"orgID" check:"id" empty:"true"`
	//是否删除
	IsRemove bool `db:"is_remove" json:"isRemove" check:"bool"`
	//搜索
	Search string `json:"search" check:"search" empty:"true"`
}

// GetSecondList 获取商品列表
func GetSecondList(args *ArgsGetSecondList) (dataList []FieldsSecond, dataCount int64, err error) {
	where := ""
	maps := map[string]interface{}{}
	where = CoreSQL.GetDeleteSQL(args.IsRemove, where)
	if args.OrgID > -1 {
		where = where + " AND org_id = :org_id"
		maps["org_id"] = args.OrgID
	}
	if args.Search != "" {
		if where != "" {
			where = where + " AND "
		}
		where = where + "(product_name ILIKE '%' || :search || '%' )"
		maps["search"] = args.Search
	}
	if args.Pages.Sort == "sort" {
		args.Pages.Sort = "sort, update_at"
	}
	tableName := "mall_second"

	dataCount, err = CoreSQL.GetListPageAndCount(
		Router2SystemConfig.MainDB.DB,
		&dataList,
		tableName,
		"id",
		"SELECT id,create_at,update_at,delete_at,start_time,end_time,product_id,product_name,price,status "+"FROM "+tableName+" WHERE "+where,
		where,
		maps,
		&args.Pages,
		[]string{"id", "create_at", "update_at", "delete_at", "start_time", "end_time", "org_id", "product_id", "product_name", "price", "status"},
	)
	if err != nil {
		return
	}
	return
}

// GetSecondByID 获取秒杀商品信息
func GetSecondByID(id int64) (data FieldsSecond) {
	_ = Router2SystemConfig.MainDB.Get(&data, "SELECT id, create_at, update_at, delete_at, start_time, end_time,org_id, product_id, product_name, price, status, second_date FROM mall_second WHERE id = $1", id)
	if data.ID < 1 {
		return
	}
	return
}

// GetSecondListAll 获取所有未结束的秒杀商品信息
func GetSecondListAll() (dataList []FieldsSecond, dataCount int64, err error) {
	var rawList []FieldsSecond
	err = Router2SystemConfig.MainDB.Select(&rawList, "SELECT id FROM mall_second  where delete_at < to_timestamp(1000000)")
	if err != nil {
		return
	}
	dataCount = int64(len(rawList))
	for _, v := range rawList {
		vData := GetSecondByID(v.ID)
		if vData.ID < 1 {
			continue
		}
		dataList = append(dataList, vData)
	}
	//反馈
	return
}

type ArgsGetSecondListData struct {
	//秒杀时间
	SecondTime string `db:"second_time"`
	//ids
	IDs string `db:"ids"`
}

// GetSecondListData 获取秒杀数据列表
func GetSecondListData(args *ArgsGetSecondList) (dataList []paramsType, dataCount int64, err error) {
	// 分页参数
	offset := (args.Pages.Page - 1) * args.Pages.Max
	pageSize := args.Pages.Max
	var rawList []FieldsSecond
	err = Router2SystemConfig.MainDB.Select(&rawList, "SELECT second_date FROM mall_second WHERE org_id = $1 GROUP BY second_date ORDER BY second_date DESC limit $2 offset $3", args.OrgID, pageSize, offset)
	if err != nil {
		return nil, 0, fmt.Errorf("获取秒杀记录失败: %w", err)
	}
	if len(rawList) < 1 {
		return nil, 0, nil // 如果没有数据，直接返回空列表和错误为nil
	}
	dataCount = int64(len(rawList))
	for _, v := range rawList {
		//查询当前日期是所有数据
		secondDataList, _, _ := GetSecondListByDate(v.SecondDate, args.OrgID)
		// 创建map根据日期分组数据
		dataMap := make(map[string][]FieldsSecond)
		for _, v1 := range secondDataList {
			if v1.ID < 1 {
				continue
			}
			dataMap[v1.SecondDate] = append(dataMap[v1.SecondDate], v1)
		}

		for _, fields := range dataMap {
			dataMapV2 := make(map[string][]FieldsSecond)
			// 循环map通过秒杀时间区间继续分组
			for _, fields2 := range fields {
				timeKey := fields2.StartTime + " ," + fields2.EndTime
				dataMapV2[timeKey] = append(dataMapV2[timeKey], fields2)
			}

			dataMapV3 := make(map[string][]productList)
			for k, fields3 := range dataMapV2 { // 修改这里，循环map的值
				var products []productList
				for _, v2 := range fields3 { // 添加一个新的循环来遍历fields3中的每个元素
					products = append(products, productList{
						ProductID: v2.ProductID,
						Title:     v2.ProductName,
						Price:     v2.Price,
						Status:    v2.Status,
						ID:        v2.ID,
					})
				}
				dataMapV3[k] = products
			}

			paramsTypeNew := paramsType{
				SecondDate: fields[0].SecondDate,
				OrgID:      fields[0].OrgID,
			}
			for k, v2 := range dataMapV3 {
				// 使用更安全的方式处理时间字符串
				times := strings.Split(k, ",")
				if len(times) != 2 {
					// 如果时间格式不正确，记录错误并跳过当前项
					fmt.Printf("时间格式错误: %s\n", k)
					continue
				}
				secondListNew := secondList{
					StartTime:   times[0],
					EndTime:     times[1],
					ProductList: v2,
				}
				paramsTypeNew.SecondList = append(paramsTypeNew.SecondList, secondListNew)
			}
			// 对 SecondList 按照 StartTime 进行排序
			sort.Slice(paramsTypeNew.SecondList, func(i, j int) bool {
				return paramsTypeNew.SecondList[i].StartTime < paramsTypeNew.SecondList[j].StartTime
			})
			dataList = append(dataList, paramsTypeNew)
		}

	}
	//反馈
	return
}

type productList struct {
	//数据id
	ID int64 `db:"id" json:"id"`
	//状态 0 未开始 1 进行中 2 已结束
	Status int `db:"status" json:"status"`
	//秒杀价格
	Price int64 `db:"price" json:"price"`
	//商品id
	ProductID int64 `db:"product_id" json:"productID"`
	//商品名称
	Title string `db:"title" json:"title"`
	//商品副标题
	TitleDes string `db:"title_des" json:"titleDes"`
	//原价
	PriceReal int64 `db:"price_real" json:"priceReal"`
	//最终价格
	FinalPrice int64 `db:"final_price" json:"finalPrice"`
	//图片url
	CoverFileURL pq.StringArray `db:"cover_file_url" json:"coverFileUrl"`
	//库存
	Count int `db:"count" json:"count"`
	//code
	Code string `db:"code" json:"code"`
}
type secondList struct {
	//秒杀开始时间
	StartTime string `db:"start_time" json:"startTime"`
	//秒杀结束时间
	EndTime string `db:"end_time" json:"endTime"`
	//商品集合
	ProductList []productList `json:"productList"`
}
type paramsType struct {
	//秒杀日期
	SecondDate string `db:"second_date" json:"secondDate"`
	//组织ID
	OrgID int64 `db:"org_id" json:"orgID"`
	//秒杀内容
	SecondList []secondList `json:"secondList"`
}

// GetSecondListByTime 获取当天时间和后一天的秒杀记录
func GetSecondListByTime(toDay, toMorrow string, orgID int64) (dataList []paramsType, dataCount int64, err error) {
	// 构建日期字符串，使用SQL安全的方式防止SQL注入
	passIDs := []string{toDay, toMorrow}
	var rawList []FieldsSecond
	err = Router2SystemConfig.MainDB.Select(&rawList, "SELECT id, create_at, update_at, delete_at, start_time, end_time, org_id, product_id, product_name, price, status, second_date FROM mall_second WHERE second_date IN ($1, $2) and org_id = $3 ORDER BY second_date, start_time", passIDs[0], passIDs[1], orgID)
	if err != nil {
		return nil, 0, fmt.Errorf("获取秒杀记录失败: %w", err)
	}

	if len(rawList) == 0 {
		return nil, 0, nil // 如果没有数据，直接返回空列表和错误为nil
	}
	// 创建map根据日期分组数据
	dataMap := make(map[string][]FieldsSecond)
	for _, v := range rawList {
		if v.ID < 1 {
			continue
		}
		dataMap[v.SecondDate] = append(dataMap[v.SecondDate], v)
	}

	for _, fields := range dataMap {
		dataMapV2 := make(map[string][]FieldsSecond)
		// 循环map通过秒杀时间区间继续分组
		for _, fields2 := range fields {
			timeKey := fields2.StartTime + " ," + fields2.EndTime
			dataMapV2[timeKey] = append(dataMapV2[timeKey], fields2)
		}

		dataMapV3 := make(map[string][]productList)
		for k, fields3 := range dataMapV2 { // 修改这里，循环map的值
			var products []productList
			for _, v2 := range fields3 { // 添加一个新的循环来遍历fields3中的每个元素
				products = append(products, productList{
					ProductID: v2.ProductID,
					Title:     v2.ProductName,
					Price:     v2.Price,
					Status:    v2.Status,
					ID:        v2.ID,
				})
			}
			dataMapV3[k] = products
		}

		paramsTypeNew := paramsType{
			SecondDate: fields[0].SecondDate,
			OrgID:      fields[0].OrgID,
		}
		for k, v := range dataMapV3 {
			// 使用更安全的方式处理时间字符串
			times := strings.Split(k, ",")
			if len(times) != 2 {
				// 如果时间格式不正确，记录错误并跳过当前项
				fmt.Printf("时间格式错误: %s\n", k)
				continue
			}
			secondListNew := secondList{
				StartTime:   times[0],
				EndTime:     times[1],
				ProductList: v,
			}
			paramsTypeNew.SecondList = append(paramsTypeNew.SecondList, secondListNew)
		}
		// 对 SecondList 按照 StartTime 进行排序
		sort.Slice(paramsTypeNew.SecondList, func(i, j int) bool {
			return paramsTypeNew.SecondList[i].StartTime < paramsTypeNew.SecondList[j].StartTime
		})
		dataList = append(dataList, paramsTypeNew)
	}

	dataCount = int64(len(dataList))
	return dataList, dataCount, nil
}

// GetSecondListByDate 根据日期查询当天的所有数据
func GetSecondListByDate(secondDate string, orgID int64) (dataList []FieldsSecond, dataCount int64, err error) {
	err = Router2SystemConfig.MainDB.Select(&dataList, "SELECT id, create_at, update_at, delete_at, start_time, end_time, org_id, product_id, product_name, price, status, second_date FROM mall_second WHERE  second_date = $1 AND org_id = $2 ", secondDate, orgID)
	return
}

// GetSecondByProductIDAndDate 根据商品id和当天日期 获取秒杀商品信息
func GetSecondByProductIDAndDate(productID int64, secondDate string) (dataList []FieldsSecond) {
	_ = Router2SystemConfig.MainDB.Select(&dataList, "SELECT id, create_at, update_at, delete_at, start_time, end_time,org_id, product_id, product_name, price, status, second_date FROM mall_second WHERE delete_at < to_timestamp(1000000) AND product_id = $1 and second_date = $2", productID, secondDate)
	return
}
